package com.edgclub.edg.task;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import com.edgclub.edg.Constant;
import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.utils.util.CommAppPrefUtils;
import com.edgclub.edg.utils.util.FileUtility;
import com.rockerhieu.emojicon.emoji.AppInfo;

import java.io.File;

/**
 * Created by Administrator on 2016/11/28.
 */
public class UpdateManager {

    private Context mContext;
    private AppInfo appInfo;

    public UpdateManager(Context context, AppInfo appInfo) {
        this.mContext = context;
        this.appInfo = appInfo;
    }

    /**
     * 检测软件更新
     */
    public void checkUpdate() {
        String version = GuZhiApplication.getInstance().getVersion();
        if (version.compareTo(appInfo.getVersion()) < 0) {
            CommAppPrefUtils appPrefUtils = new CommAppPrefUtils(mContext);
            if(appPrefUtils.isDown()){
                File file = new File(Constant.apkDir + appInfo.getVersion() + ".apk");
                if (file.exists()) {
                } else {
                    appPrefUtils.saveDown(false);
                    new downloadApkThread().start();
                }
            } else {
                appPrefUtils.saveDown(false);
                new downloadApkThread().start();
            }

        }
    }

    /**
     * 下载文件线程
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                FileUtility.loadFileFromUrl(appInfo.getUrl(), Constant.apkDir + appInfo.getVersion() + ".apk");
                CommAppPrefUtils appPrefUtils = new CommAppPrefUtils(mContext);
                appPrefUtils.saveDown(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 安装APK文件
     */
    public void installApk() {
        File apkfile = new File(Constant.apkDir + appInfo.getVersion() + ".apk");
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }
}
